package com.linln.wtp.config;

import com.linln.common.utils.PathMappingUtil;
import com.linln.common.utils.SignUtil;
import com.linln.common.vo.JsonResult;
import com.linln.component.cache.util.RedisUtil;
import org.apache.logging.log4j.util.PropertiesUtil;
import org.elasticsearch.common.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Configuration
public class WxMyWebMvcConfigurer implements WebMvcConfigurer {

    @Value("${API.APPID}")
    private String APPID;
    @Value("${API.APPSECRET}")
    private String SECRET;
//    @Value("${server.whitelist}")
//    private String  WHITELIST;
//    @Value("${server.MAINTAIN}")
//    private String  MAINTAIN;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                response.setContentType("text/html;charset=utf-8");

/*                String ip = request.getHeader("x-forwarded-for");
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_CLIENT_IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }

                if(!WHITELIST.contains(ip)&&MAINTAIN.equals("1")){
                    JsonResult.error("系统维护中");
                }*/

                String appid = request.getHeader("appid");
                String sign = request.getHeader("sign");
                String nonce = request.getHeader("nonce");
                String timestamp = request.getHeader("timestamp");

                if (Strings.isEmpty(appid) || Strings.isEmpty(timestamp) || Strings.isEmpty(nonce) || Strings.isEmpty(sign)) {
                    response.getWriter().println(JsonResult.error("请求头缺少授信参数"));
                    return false;
                }

                // 限制为（含）60秒以内发送的请求
                long time = 60000;
                long now = System.currentTimeMillis();
                if (now - Long.parseLong(timestamp) > time) {
                    response.getWriter().println(JsonResult.error("请求发起时间超过服务器限制时间"));
                    return false;
                }
                // 校验appid
                if (!APPID.equalsIgnoreCase(appid)) {
                    response.getWriter().println(JsonResult.error("appid参数错误"));
                    return false;
                }

                if (redisUtil.hHasKey("third_party_key", APPID + nonce)) {
                    response.getWriter().println(JsonResult.error("请不要发送重复的请求"));
                    return false;
                } else {
                    // 如果nonce没有存在缓存中，则加入，并设置失效时间（秒）
                    redisUtil.hset("third_party_key", APPID + nonce, nonce);
                    redisUtil.expire("third_party_key", (int)time/1000);
                }
                Map<String, String> signObj = new HashMap<>(3);
                signObj.put("appid", appid);
                signObj.put("timestamp", timestamp);
                signObj.put("nonce", nonce);
                String mySign = SignUtil.getSign(signObj, SECRET);
                // 校验签名
                if (!mySign.equals(sign)) {
                    response.getWriter().println(JsonResult.error("签名信息错误"));
                    return false;
                }
                return true;
            }
        }).addPathPatterns("/**").excludePathPatterns(PathMappingUtil.getFilterMapping()).excludePathPatterns("/wx").excludePathPatterns("/image2Info");//过滤的图片路径
    }

}
